package com.asen.commons.core.jdbc.builder.mysql.filter;

import com.asen.commons.core.jdbc.exception.JdbcException;
import com.asen.commons.core.jdbc.param.SqlColumn;
import com.asen.commons.core.jdbc.param.SqlContextManager;
import com.asen.commons.core.meta.dao.FilterItem;

/**
 * 数值类型过滤解析器
 *
 * @author Gary
 * @version 1.0
 * @date 2021-08-22
 */
public class NumberFilterParser implements FilterParser {

    @Override
    public CharSequence parse(SqlContextManager contextManager, FilterItem filterItem) {
        SqlColumn sqlColumn1 = contextManager.getSqlColumn(filterItem.getFieldName());
        SqlColumn sqlColumn2 = contextManager.getSqlColumn(filterItem.getFieldName2());
        if (sqlColumn1 == null || sqlColumn2 == null) {
            return null;
        }

        StringBuilder sql = new StringBuilder();
        if (filterItem.getSymbol().name().endsWith("_ABS")) {
            sql.append("(")
                    .append(absColumn(sqlColumn1))
                    .append("-")
                    .append(absColumn(sqlColumn2))
                    .append(")")
                    .append(filterItem.getSymbol().getDesc());
        } else {
            sql.append("(")
                    .append(numberColumn(sqlColumn1))
                    .append("-")
                    .append(numberColumn(sqlColumn2))
                    .append(")")
                    .append(filterItem.getSymbol().getDesc());
        }

        Object value = filterItem.getValue();
        if (value == null) {
            sql.append("0");
        } else {
            sql.append("?");
            contextManager.setParam(sqlColumn1.getJavaType(), value);
        }
        return sql;
    }

    private String numberColumn(SqlColumn sqlColumn) {
        if (Number.class.isAssignableFrom(sqlColumn.getJavaType())) {
            return "IFNULL(" + sqlColumn.getFullColumn() + ",0)";
        }
        throw new JdbcException("非数值类型不能使用Compare方法！");
    }

    private String absColumn(SqlColumn sqlColumn) {
        if (Number.class.isAssignableFrom(sqlColumn.getJavaType())) {
            return "ABS(IFNULL(" + sqlColumn.getFullColumn() + ",0))";
        }
        throw new JdbcException("非数值类型不能使用Compare方法！");
    }

}
